package com.geese.module.security.service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.geese.common.entity.Role;
import com.geese.common.entity.RolePermission;
import com.geese.common.util.BeanUtil;
import com.geese.common.util.PageUtil;
import com.geese.common.vo.Page;
import com.geese.common.vo.Paginator;
import com.geese.exception.BusinessException;
import com.geese.module.admin.dto.RoleDto;
import com.geese.module.admin.vo.RoleQuery;
import com.geese.module.security.dao.RoleMapper;
import com.geese.module.security.dao.RolePermissionMapper;
import com.geese.module.security.dao.UserRoleMapper;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;

/**
 * Created by Z先生 on 2017/2/27.
 */
@Service
public class RoleService {

    @Autowired
    RolePermissionMapper rolePermissionMapper;

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;


//    public List<Role> findAll() {
//        return roleMapper.findAll();
//    }
//
//    public void addRolePer(int id, Set list) {
//        for (Object str : list) {
//            rolePermissionMapper.saveRolePermission(id,str);
//        }
//    }
//
//    public void deleteRolePer(int id, Set<String> list) {
//        for (String str : list) {
//            rolePermissionMapper.deleteRolePermission(id,str);
//        }
//    }
//

    /**
     * 根据userId获取角色列表
     */
	public List<Role> listByUserId(Integer userId) {
		List<Integer> roleIds = userRoleMapper.listByUserId(userId);
		if(CollectionUtils.isEmpty(roleIds)) {
			return Lists.newArrayList();
		}
		return roleMapper.listByIds(roleIds);
	}

	/**
	 * 新增角色
	 */
	public void save(Role role, List<Integer> permissionIds) {
		Role nameRole = roleMapper.findByDescription(role.getDescription());
		if(nameRole != null) {
			throw new BusinessException(130004);
		}
		role.setEnable(1);
		role.setCreateTime(new Date());
		role.setIsDefault(0);
		roleMapper.save(role);
		List<RolePermission> rolePermissionList = getRolePermissionList(role.getId(), permissionIds);
		rolePermissionMapper.batchSave(rolePermissionList);
	}
	
	/**
	 * 编辑角色
	 */
	public void update(Role role, List<Integer> permissionIds) {
		Role model = roleMapper.findById(role.getId());
		if(model == null) {
			throw new BusinessException(120009);
		}
		if(Objects.equals(model.getIsDefault(), 1)) {
			throw new BusinessException(130005);
		}
		Role nameRole = roleMapper.findByDescription(role.getDescription());
		if(nameRole != null && !Objects.equals(model.getId(), nameRole.getId())) {
			throw new BusinessException(130004);
		}
		model.setDescription(role.getDescription());
		model.setMemo(role.getMemo());
		roleMapper.update(model);
		rolePermissionMapper.removeByRoleId(model.getId());
		List<RolePermission> rolePermissionList = getRolePermissionList(role.getId(), permissionIds);
		rolePermissionMapper.batchSave(rolePermissionList);
	}
	
	/**
	 *  删除角色
	 */
	public void remove(Integer roleId) {
		Role model = roleMapper.findById(roleId);
		if(model == null) {
			throw new BusinessException(120009);
		}
		if(Objects.equals(model.getIsDefault(), 1)) {
			throw new BusinessException(130005);
		}
		List<Integer> userIds = userRoleMapper.listByRoleId(model.getId());
		if(CollectionUtils.isNotEmpty(userIds)) {
			throw new BusinessException(130006);
		}
		roleMapper.remove(model.getId());
		rolePermissionMapper.removeByRoleId(model.getId());
	}

	/**
	 * 获取角色详情
	 */
	public RoleDto findById(Integer id) {
		Role model = roleMapper.findById(id);
		if(model == null) {
			throw new BusinessException(120009);
		}
		List<Integer> permissionList = rolePermissionMapper.listByRoleId(id);
		RoleDto result = BeanUtil.map(model, RoleDto.class);
		result.setPermissionList(permissionList);
		return result;
	}
	
	/**
	 * 获取角色列表
	 */
	public Paginator<Role> listAllByQuery(RoleQuery query, Page page) {
		PageHelper.startPage(page.getCurrPage(), page.getPageSize(), "create_time desc");
		List<Role> roleList = roleMapper.listAllByQuery(query);
		return PageUtil.getPage(roleList);
	}

	private List<RolePermission> getRolePermissionList(Integer roleId, List<Integer> permissionIds) {
		List<RolePermission> result = Lists.newArrayList();
		if(CollectionUtils.isEmpty(permissionIds)) {
			return result;
		}
		RolePermission temp = null;
		for(Integer id : permissionIds) {
			temp = new RolePermission();
			temp.setEnable(1);
			temp.setPermissionId(id);
			temp.setRoleId(roleId);
			result.add(temp);
		}
		return result;
	}

}
